package com.gxa.ibear.interceptor;

import com.gxa.ibear.common.ErrorCode;
import com.gxa.ibear.common.RedisConst;
import com.gxa.ibear.exception.BizException;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Lenovo
 */
@Component
public class TokenBucketInterceptor implements HandlerInterceptor {

    RedisTemplate<String,Object> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //请求热点数据的时候才需要限流

        ListOperations<String, Object> listOperations = redisTemplate.opsForList();
        Long size = listOperations.size(RedisConst.TOKEN_BUCKET);
        if (size!=null && size<=0){
            throw new BizException(ErrorCode.LACK_TOKEN);
        }
        redisTemplate.opsForList().rightPop(RedisConst.TOKEN_BUCKET);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
         redisTemplate.opsForList().leftPush(RedisConst.TOKEN_BUCKET,1);

    }
}
